package com.hg.observer;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: skh
 * @Date: 2018/10/29 10:14
 * @Description: 主题
 */
public class Subject implements Observable{
    private List<Observer> observers = new ArrayList<>();
    private Boolean hasChanged = false;


    @Override
    public void addObserver(Observer observer) {
        observers.add(observer);
    }

    @Override
    public void deleteObserver(Observer observer) {
        observers.remove(observer);
    }

    @Override
    public void notifyObserver() {
        if (!hasChanged) {
            return;
        }
        for (Observer observer : observers) {
            observer.update(this,null);
        }
    }

    @Override
    public void notifyObserver(Object arg) {
        if (!hasChanged) {
            return;
        }
        for (Observer observer : observers) {
            observer.update(this,arg);
        }
    }

    @Override
    public void deleteObservers() {
        observers.clear();
    }

    @Override
    public void setChanged() {
        hasChanged = true;
    }

    @Override
    public void clearChanged() {
        hasChanged=false;
    }

    @Override
    public Boolean hasChanged() {
        return hasChanged;
    }

    @Override
    public Integer countObservers() {
        return observers.size();
    }
}
